<?php
class KnowledgeAction extends PublicAction {
	public function index(){
		$knowledgeview = D('KnowledgeView');
		$knowledgelist=$this->category_search($knowledgeview);
		if(!$knowledgelist){
			$statusx = 1;
		}else{
			$statusx = 0;
		}
		//获取最近检索词
		$zkeywords=$_SESSION['zkeyword'];
		$this->assign('zkeywords',$zkeywords);
		$this->assign('statusx',$statusx);
		$this->assign('list',$knowledgelist);
		$this->assign('cate',$cates);
		$this->display();
	}
    
    
	
	public function upload(){
		header('Content-Type:text/html;charset=utf8');
		if(!session(C('USER_AUTH_KEY')) && !session(C('ADMIN_AUTH_KEY')))
		{
			$this->redirect('User/login');
		}else{
			$uid=getUserInfo('uid');
	   		$basic=M('User')->find($uid); 
	   		if($basic['status'] == 2){
			  	if(session(C("USER_AUTH_KEY")))
				{
					if(session(C("USER_AUTH_KEY"))){
						session(C("USER_AUTH_KEY"),NULL);	
					}
					cookie(C('USER_AUTH_ACCOUNT'),null,-3600);
					cookie(C('USER_AUTH_PWD'),null,-3600);
				}
				$this->redirect('User/login');
	  		 }
			$model=M('Category');
			$map['status'] = 1;
			$map['catepid'] = 9;
			$list=$model->where($map)->select();
			$this->assign('list',$list);
			if($_GET['success']){
				$this->assign('error',$_GET['error']);
				$this->assign('val',$_GET['success']);	
			}else{
				$this->assign('val',0);	
			}
	        $this->display();
		}
	}
	
	public function getSwf($sourceFile,$destFile){
			
		//echo "begin...<br/>";
			#exec("/usr/local/swftools/bin/pdf2swf qx.pdf -o ok.swf",$arrOut,$retVal);
		$pdflujing=$sourceFile.'.pdf';
		exec("./Public/zhuanhuan/doc2pdf $sourceFile $pdflujing",$arrOut,$retVal);
		exec("./Public/zhuanhuan/pdf2swft $pdflujing $destFile",$arrOut,$retVal);
		//echo "<pre>";
		//print_r($arrOut);
			
		//echo "end...<br/>";
		//echo "retVal: ".$retVal;
		#pclose($fp);
	}
	
	/**
	 * $filename  文件名（带文件路径）
	 * return	  true OR false
	 */
	public function txt2utf8($filename){
		if(pathinfo($filename, PATHINFO_EXTENSION) == 'txt'){
			$filedata = file_get_contents($filename); 	
			$filetype = mb_detect_encoding($filedata , array('UTF-8','GBK','LATIN1','BIG5'));
			if( $filetype != 'UTF-8'){ 
		    	$fileda = iconv($filetype ,'utf-8',$filedata);
		    	if(file_put_contents($filename , $fileda )){
		    		return true;
		    	}else{
		    		return false;
		    	}
			}else{
				return true;
			}
		}else{
			return true;
		}
	}
	
	public function knowledgeupload(){
		   if(!empty($_FILES)){
				$imageurl['0'] = $_FILES['imageurl'];
				$url['0'] = $_FILES['url'];
				if ($imageurl['0']['name']){
					$imageurlList = uploadsource('-1','jpg,gif,png,jpeg','./Public/Uploads/Knowledge/Image/',$imageurl,true,'m_','140','125');
					if(is_array($imageurlList)){
						 $_POST['imageurl'] = $imageurlList[0]['savename'];
					}else{
			        	 $this->error($imageurlList);
			        }
				}
			$urlList = uploadsource('-1','doc,txt,docx','./Public/Uploads/Knowledge/',$url);
			if(is_array($urlList)){
				 $_POST['url'] = $urlList[0]['savename'];
			}else{
				unlink('./Public/Uploads/Knowledge/Image/'.$_POST['imageurl']);
				unlink('./Public/Uploads/Knowledge/Image/m_'.$_POST['imageurl']);
	        	$this->error($urlList);
	        }
			$model = D('Knowledge');
	        $data = $_POST;
	        $data['imageurl'] = $_POST['imageurl'];
	        $data['url'] = $_POST['url'];
	        
	        /*$sourceFile='./Public/Uploads/Knowledge/'.$_POST['url'];
			$destFile='./Public/Uploads/Knowledge/Swf/'.$_POST['url'].'.swf';
		    if($this->txt2utf8($sourceFile)){
	        	$this->getSwf($sourceFile,$destFile);
			}*/
	        
	        if($model->create($data))
			{   
			   	$list = $model->add();
		        if ($list !== false) {
		        	$map['kid'] = $list;
		        	$datas['code'] = 'k'.$list;
		        	$lists = $model->where($map)->save($datas);
		        	$this->redirect('Knowledge/upload',array('success'=>2));
		        } else {
		        	unlink('./Public/Uploads/Knowledge/Image/'.$_POST['imageurl']);
					unlink('./Public/Uploads/Knowledge/Image/m_'.$_POST['imageurl']);
					unlink('./Public/Uploads/Knowledge/'.$_POST['url']);
		             $this->redirect('Knowledge/upload',array('success'=>1,'error'=>$model->getError()));
		        }
			}else{
				unlink('./Public/Uploads/Knowledge/Image/'.$_POST['imageurl']);
				unlink('./Public/Uploads/Knowledge/Image/m_'.$_POST['imageurl']);
				unlink('./Public/Uploads/Knowledge/'.$_POST['url']);
				$this->redirect('Knowledge/upload',array('success'=>1,'error'=>$model->getError()));
			}
		}
	}
//验证码
	public function verify(){
    	import("ORG.Util.Image");	
		Image::buildImageVerify();
	}
	//显示资源库下的分类
	
	public function showsid(){
	    if(!session(C('USER_AUTH_KEY')) && !session(C('ADMIN_AUTH_KEY')))
		$this->redirect('User/login');
		$pid = $_POST['pid'];
		if($pid){
			$map['catepid'] = $pid;
			$map['status'] = 1;
			$resl = M('Category')->where($map)->select();
			if($resl){
				$res = "<option value='0' selected >选择分类</option>";
				foreach ($resl as $key => $value){
					$res .= "<option value='". $value['cateid'] ."'  name='cateid'>" . $value['catename'] . "</option>";
				}
				$res="<select name='cateid' id='cateid' class='cateid' style='width:145px;'>".$res."</select>";
				echo $res;
			}else{
				//$res = "<option value='0' selected >新建分类</option>";
				echo 0;
			}
		}else{
			echo 0;
		}
	}
	public function checkverify(){
	    if(!session(C('USER_AUTH_KEY')) && !session(C('ADMIN_AUTH_KEY')))
		$this->redirect('User/login');
		$val=md5($_POST['val']);
		if($val){
		 if($_SESSION['verify'] !=$val) echo 1;
		 else echo 0;
		}
	}
	
	/**
	 * 下载
	 * @author 沈威
	 * @tel 15005164276
	 * @email 403382132@qq.com
	 * Enter 
	 **/
	public function knowledgedownload(){
	if(!session(C('USER_AUTH_KEY')) && !session(C('ADMIN_AUTH_KEY'))) $this->redirect('User/login');
		$uid=getUserInfo('uid');
   		$basic=M('User')->find($uid); 
   		if($basic['status'] == 2){
		  	if(session(C("USER_AUTH_KEY")))
			{
				if(session(C("USER_AUTH_KEY"))){
					session(C("USER_AUTH_KEY"),NULL);	
				}
				cookie(C('USER_AUTH_ACCOUNT'),null,-3600);
				cookie(C('USER_AUTH_PWD'),null,-3600);
			}
			echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head>";
  			echo "<body><script>alert('您的帐号已被禁用');history.go(-1)</script></body></html>";
  			exit;
  		 }
	
	if($_POST){
	  	if($_POST['prescore']<$_POST['score'])
	  	{
	  		echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head>";
	  		echo "<body><script>alert('下载失败,您的积分不足');history.go(-1)</script></body></html>";
	  	}
	  	else
	  	{
	  		//$count=$_POST['count'];
		  $pid=$_POST['kid'];
	      $title=$_POST['title'];
	  	  $file_dir="./Public/Uploads/Knowledge/";
	  	  $picture=M('Exhibits')->where("kid=$pid")->find();
	  	  //$url = explode(',', $picture['url']);
		  $file_name=$_POST['url'];
		  $score='-'.$_POST['score'];
		  $addscore=$_POST['score'];
		  $code=$_POST['code'];
		  $reason="下载'".$title."'";
		  $addreason="'".$title."'被下载";
		  $this->assign('prescore',$_POST['prescore']);
	      $uid=getUserInfo('uid',false);
		  $msg=M('Knowledge')->field('uid')->find($pid);
		  $adduid=$msg['uid'];
		  $map=array('uid'=>$uid,'code'=>$code);
		  $record=M('Score')->where($map)->find();
		  download($file_dir,$file_name,$title);
	      M('Knowledge')->where("kid=$pid")->setInc('point');
	      if($_POST['once']==1)
	      {
			  if(!in_array($code,$record))
			  {
				  income($uid,$score,$reason,$code);
				  income($adduid,$addscore,$addreason,$code);
	          }
	      }
	  	}
	  }
	}
	
	/**
	 * 点评
	 * @author 沈威
	 * @tel 15005164276
	 * @email 403382132@qq.com
	 * Enter description here ...
	 */
	public function fbcomment(){
		
		$uid=getUserInfo('uid');
   		$basic=M('User')->find($uid); 
   		if($basic['status'] == 2){
		  	if(session(C("USER_AUTH_KEY")))
			{
				if(session(C("USER_AUTH_KEY"))){
					session(C("USER_AUTH_KEY"),NULL);	
				}
				cookie(C('USER_AUTH_ACCOUNT'),null,-3600);
				cookie(C('USER_AUTH_PWD'),null,-3600);
			}
			echo "您已被禁用！";
			exit;
  		 }
		
		if(getUserInfo('uid')){
			$cond = $_POST;
			$cond['comuid'] = getUserInfo('uid');
			$cond['_column'] = array('comtype','comcontent','commid','commname','comuid');
			foreach ($cond['_column'] as $one) $data[$one] = trim($cond[$one]);
			$model = D('Comment');
			if($model->create($data))
			{
				if(($comid = $model->add())!= false){
					echo "评论成功，审核通过后可显示。";
				}else{
					echo "评论失败";
				}
			}else{
				echo $model->getError();
			}
		}else{
			echo "登录后才能发表评论";
		}
	}
	
	/**
	 * 跳转致知识题三级页面
	 * @author 沈威
	 * @tel 15005164276
	 * @email 403382132@qq.com
	 * Enter description here ...
	 */
	public function info()
	{   
		$kid=$_GET['vid'];
		$map['kid']=$kid;
		$view = D('KnowledgeView');
		$knowledge=$view->where($map)->find();
		$knowledgeinfo = M('Knowledge')->where($map)->find();
		if(($knowledgeinfo['is_dele']==1)||($knowledgeinfo['status'])==0)
			{
				$this->error("此资源已被删除,或未通过审核!");
			}
		$knowledge['desc'] = $knowledgeinfo['desc'];
		$user = M('User');
		$lap['uid']=$knowledge['uid'];
		$username=$user->where($lap)->getField('username');
		$knowledge['username']=$username;
		$this->assign('knowledge',$knowledge);
		//获取相关知识题
		$dap['status']=1;
		$dap['is_dele']=0;
		//$dap['cateid']=$knowledge['cateid'];
		$dap['kid']  = array('NEQ',$kid);
		$keyword=explode('|', $knowledge['keyword']);
		for($m=0;$m<count($keyword);$m++)
		{
			if($m!=count($keyword)-1)
			{
				$liketitle .= ' (title like \'%'.$keyword[$m].'%\')  OR ' ;
			}
			else 
			{
				$liketitle .= ' (title like \'%'.$keyword[$m].'%\')   ' ;
			}
		}
		$dap['_string']=$liketitle;
		$xlist=$view->where($dap)->limit('0,8')->select();
		if($xlist){
			$xsta = 1;
		}else{
			$xsta = 0;
		}
		$this->assign('xsta',$xsta);
		$this->assign('xlist',$xlist);	
		//获取热门知识题
		$sap['status']=1;
		$sap['is_dele']=0;
		$rlist=$view->where($sap)->limit('0,8')->order('point desc')->select();
		if($rlist){
			$rsta = 1;
		}else{
			$rsta = 0;
		}
		$this->assign('rsta',$rsta);
		$this->assign('rlist',$rlist);			
	 //获取当前积分 
		if(session(C('USER_AUTH_KEY')) || session(C('ADMIN_AUTH_KEY')))
		{	
		$uid=getUserInfo('uid',false);
	   //$uid=getUserInfo('uid');
	   $found=M('User')->where("`uid`=$uid")->field('score')->find();
	   $score=$found['score'];
       $this->assign('prescore',$score);
		}
       //获取资源评论
			import("ORG.Util.Page");
			$comment = M('Comment');
			$user = M('User');
			$qaps['comtype'] = 9;
			$qaps['comstatus'] = 0;
			$qaps['commid'] = $_GET['vid'];
			
			$pgnum = 5;
			if(strtolower($_SERVER['REQUEST_METHOD']) == 'post'){
				if($_POST['pgnum']){
					$pgnum = $_POST['pgnum'];
				}
			}
			$count = $comment->where($qaps)->count();
			$page_com = new Page($count,$pgnum);
			
			$list = $comment->where($qaps)->limit($page_com->firstRow.",".$page_com->listRows)->order('comtime desc')->select();
			foreach($list as $key => $val){
				$mapss['uid'] = $val['comuid'];
				$userinfo = $user->field('nickname,image')->where($mapss)->find();
				$list[$key]['nickname'] = $userinfo['nickname'];
				if($userinfo['image']){
					$list[$key]['image'] = $userinfo['image'];
				}else{
					$list[$key]['image'] = "per_img.jpg";
				}
			}
			$this->assign('list',$list);
			$this->assign("page_com",$page_com->show());
			$this->assign("count",$count);
			//获取当前位置
			$hap['cateid']=$knowledge['cateid'];
			$catefory_model=M('Category');
			$catefory=$catefory_model->where($hap)->find();
			$cate=$catefory['catename'];
			if($catefory['catepid']!=9)
			{
				$rap['cateid']=$catefory['catepid'];
				$erjicate=$catefory_model->where($rap)->find();
				$erjicatename=$erjicate['catename'];
			}
			$this->assign("erjicate",$erjicatename);
			$this->assign("erjicateid",$catefory['catepid']);
			$this->assign("cate",$cate);
	   $this->display();

	}
}